﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;
using ICDA.DataModels.ICDA;
using jqGrid.Models.ICDA;

namespace ICDA.Repositories.ICDA
{
    public class ProductsRepository : IProductsRepository
    {
        #region Fields
        NorthWindDataContext _dataContext = new NorthWindDataContext();
        #endregion

        #region IProductsRepository Members
        public int GetProductsCount(string filterExpression)
        {
            if (!String.IsNullOrWhiteSpace(filterExpression))
                return _dataContext.Products.Where(filterExpression).Count();
            else
                return _dataContext.Products.Count();
        }

        public IQueryable<Product> GetProducts(string filterExpression, string sortExpression, string sortDirection, int pageIndex, int pageSize, int pagesCount)
        {
            if (!String.IsNullOrWhiteSpace(filterExpression))
                return _dataContext.Products.Where(filterExpression).OrderBy(sortExpression + " " + sortDirection).Skip(pageIndex * pageSize).Take(pageSize);
            else
                return _dataContext.Products.OrderBy(sortExpression + " " + sortDirection).Skip(pageIndex * pageSize).Take(pagesCount * pageSize);
        }

        public Product GetProduct(int productId)
        {
            return _dataContext.Products.First(p => p.ProductID == productId);
        }

        public bool DeleteProduct(int productId)
        {
            try
            {
                _dataContext.Products.DeleteOnSubmit(_dataContext.Products.First(p => p.ProductID == productId));
                _dataContext.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                return false;
            }
        }

        public bool AddProduct(Product product)
        {
            try
            {
                _dataContext.Products.InsertOnSubmit(product);
                _dataContext.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                return false;
            }
        }

        public void SubmitChanges()
        {
            _dataContext.SubmitChanges();
        }
        #endregion
    }
}